package logic

import (
	"context"
	"errors"
	"manuscript-service/moders/mysql"

	"manuscript-service/manrpc/internal/svc"
	"manuscript-service/manrpc/manrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptAddLogic {
	return &ManuscriptAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManuscriptAddLogic) ManuscriptAdd(in *manrpc.ManuscriptAddRequest) (*manrpc.ManuscriptAddResponse, error) {
	// todo: add your logic here and delete this line

	var FindManuscript mysql.Manuscript

	begin := mysql.DB.Begin()

	err := FindManuscript.FindManuscriptName(begin, in.Title)
	if err == nil {
		return nil, errors.New("稿件已存在")
	}

	var class mysql.Class
	class = mysql.Class{
		Name: in.Name,
	}
	err = class.ClassName(begin, in.Name)
	if err != nil {
		return nil, err
	}

	manuscript := &mysql.Manuscript{
		Title:   in.Title,
		Price:   int(in.Price),
		ClassId: int(in.ClassId),
	}
	err = manuscript.ManuscriptAdd(begin)
	if err != nil {
		return nil, err
	}
	begin.Commit()
	return &manrpc.ManuscriptAddResponse{
		ManuscriptId: int64(class.ID),
	}, nil
}
